package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.AdminMapper;
import com.qingcheng.dao.AdminRoleMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.org.mindrot.jbcrypt.BCrypt;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.entity.AdminAdd;
import com.qingcheng.pojo.system.AdminRole;
import com.qingcheng.service.system.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = AdminService.class)
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Admin> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectAll();
        return new PageResult<Admin>(admins.getTotal(), admins.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Admin> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return adminMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Admin> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectByExample(example);
        return new PageResult<Admin>(admins.getTotal(), admins.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public AdminAdd findById(Integer id) {
        AdminAdd adminAdd=new AdminAdd();
        Admin admin = adminMapper.selectByPrimaryKey(id);
        adminAdd.setAdmin(admin);
        Example example=new Example(AdminRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId",id);
        List<AdminRole> adminRoles = adminRoleMapper.selectByExample(example);
        List<Integer> list=new ArrayList<Integer>();
        if (adminRoles!=null&&adminRoles.size()>0){
            for (AdminRole adminRole : adminRoles) {
                list.add(adminRole.getRoleId());
            }
        }
        adminAdd.setRoleIds(list);
        return adminAdd;
    }

    /**
     * 新增
     *
     * @param adminAdd
     */
    @Transactional
    public void add(AdminAdd adminAdd) {
        Admin admin = adminAdd.getAdmin();
        //密码加密操作
        String password = admin.getPassword();
        String gensalt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw(password, gensalt);
        admin.setPassword(hashpw);
        int adminId = adminMapper.insert(admin);
        //存储中间表
        List<Integer> roleIds = adminAdd.getRoleIds();
        this.addAminRole(adminId, roleIds);
    }

    /**
     * 修改
     *
     * @param adminAdd
     */
    @Transactional
    public void update(AdminAdd adminAdd) {
        Admin admin = adminAdd.getAdmin();
        String password = admin.getPassword();
        if (password==null||"".equals(password)){
            admin.setPassword(null);
        }else{
            String s = BCrypt.gensalt();
            String hashpw = BCrypt.hashpw(password, s);
            admin.setPassword(hashpw);
        }
        adminMapper.updateByPrimaryKeySelective(admin);
        Integer adminId = admin.getId();

        Example example=new Example(AdminRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId",adminId);
        adminRoleMapper.deleteByExample(example);

        List<Integer> roleIds = adminAdd.getRoleIds();
        this.addAminRole(adminId, roleIds);
    }

    private void addAminRole(Integer adminId, List<Integer> roleIds) {
        if (roleIds!=null&&roleIds.size()>0){
            for (Integer roleId : roleIds) {
                AdminRole adminRole = new AdminRole();
                adminRole.setAdminId(adminId);
                adminRole.setRoleId(roleId);
                adminRoleMapper.insert(adminRole);
            }
        }
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改用户密码
     *
     * @param name
     * @param map
     */
    public void alterPassword(String name, Map map) {
        String oldPassword = (String) map.get("oldPassword");
        String newPaasword = (String) map.get("newPaasword");
        Example example = new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName", name);
        List<Admin> admins = adminMapper.selectByExample(example);
        if (admins == null || admins.size() == 0) {
            throw new RuntimeException("用户名错误");
        }
        Admin admin = admins.get(0);
        String password = admin.getPassword();
        boolean checkpw = BCrypt.checkpw(oldPassword, password);
        if (checkpw == false) {
            throw new RuntimeException("原密码错误");
        }
        String gensalt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw(newPaasword, gensalt);
        admin.setPassword(hashpw);
        adminMapper.updateByPrimaryKey(admin);
    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 用户名
            if (searchMap.get("loginName") != null && !"".equals(searchMap.get("loginName"))) {
                criteria.andEqualTo("loginName", searchMap.get("loginName"));
            }
            // 密码
            if (searchMap.get("password") != null && !"".equals(searchMap.get("password"))) {
                criteria.andEqualTo("password", searchMap.get("password"));
            }
            // 状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // id
            if (searchMap.get("id") != null) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }

        }
        return example;
    }

}
